<?php

class stPostcardCard_model extends stmodel_2_1 {

    public function __construct($config) {
        parent::__construct($config);
        $this->setTableName($this->prefix . 'st_postcard_card');
        $this->setPrimaryKey('id');
        $fucntionName = $this->config['plugin_name'] . "Functions";
        $this->functions = new $fucntionName($this->config);
    }

    public function saveStPostcardCard($data) {
        $upload_dir = wp_upload_dir();
        if (!empty($data['logo_file'])) {

            $info = pathinfo($data['logo_file']);
            if ($info['extension'] == 'gif') {
                $name = basename($data['logo_file']);
                $img_url = $upload_dir['path'] . '/' . $name;

                $srcImg = imagecreatefromgif($img_url);
                unlink($img_url);

                $filename = $upload_dir['path'] . '/logo_' . time() . '-thumb.png';
                imagepng($srcImg, $filename);
                imagedestroy($srcImg);

                $name = basename($filename);
                $data['logo_file'] = $upload_dir['subdir'] . '/' . $name;
            } else {
                $name = basename($data['logo_file']);
                if (!@strpos($name, 'thumb')) {
                    $name = explode('.', $name);
                    $name = $name[0] . '-thumb' . '.' . $name[1];
                }
                $data['logo_file'] = $upload_dir['subdir'] . '/' . $name;
            }
        }
        if ($data['featured'] == 1) {
            $priority = $this->getPriority($data['id']);
            if($priority == 0){
                $data['priority'] = $this->getMaxPriority() + 1;
            }               
        } else {
            $data['priority'] = 0;
        }
        return $this->saveRecords($data);
    }

    public function saveStPostcardCardList($objects, $bucket) {
        foreach ($buckets as $value) {
            $data['id'] = NULL;
            $data['name'] = $value;
            $data['cdate'] = date('Y-m-d H:i:s');
        }
        return $this->saveRecords($data);
    }

    public function getRecords($args = '', $extra_sql = '') {
        $default_args = array(
            'fields' => '*',
            'and_where' => '',
            'or_where' => '',
            'where' => '',
            'order' => '',
            'limit' => '',
            'group_by' => '',
            'custom_query' => '',
        );
        if ($args == '')
            $args = $default_args;

        $fields = $args['fields'] ? $args['fields'] : '*';
        $and_where = $args['and_where'] ? $args['and_where'] : '';
        $or_where = $args['or_where'] ? $args['or_where'] : '';
        $custom_where = $args['where'] ? $args['where'] : '';
        $order = $args['order'] ? $args['order'] : '';
        $limit = $args['limit'] ? $args['limit'] : '';
        $group_by = $args['group_by'] ? $args['group_by'] : '';
        $custom_query = $args['custom_query'] ? $args['custom_query'] : '';
        if (!empty($custom_query)) {
            $query = $custom_query;
        } else {
            if ($fields != '*')
                $fields = implode(', ', $fields);
            //
            $where = ' WHERE ';

            if ($and_where != '')
                $where .= implode('', $and_where);
            if ($or_where != '')
                $where .= implode('', $or_where);
            if ($custom_where != '')
                $where .= $custom_where;
            if ($where == ' WHERE ')
                $where = '';
            //
            if ($order != '')
                $order = ' ORDER BY ' . implode(' ', $order);
            //
            if ($limit != '')
                $limit = ' LIMIT ' . implode(', ', $limit);
            if ($group_by != '')
                $group_by = ' GROUP BY ' . $group_by;

            $query = "SELECT $fields
            FROM $this->_tableName card
            $extra_sql
            $where
            $group_by
            $order
            $limit
            ";
        }
//        echo $query;
        return $this->get_results($query);
    }

    public function countRecords($args = '', $extra_sql = '') {

        $result = $this->getRecords($args, $extra_sql);
        return count($result);
    }

    public function getLastId() {
        $query = "SELECT max(id)
        FROM $this->_tableName
        ";
        $result = $this->get_var($query);
        return $result + 1;
    }

    public function getCardName($card_id) {
        $query = "SELECT name
        FROM {$this->_tableName}
        WHERE `id` = $card_id        
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function getCatId($card_id) {
        $query = "SELECT cat_id
        FROM {$this->_tableName}
        WHERE `id` = $card_id        
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function getPhotographer($card_id) {
        $query = "SELECT photographer
        FROM {$this->_tableName}
        WHERE `id` = $card_id        
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function getTotalUser() {
        $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
        $query = "SELECT count(id)
        FROM {$this->prefix}st_postcard_user
        WHERE smt_user_id = $smt_user_id       
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function getTotalCards() {
        $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
        $current_folder = $this->config['folder_generated'];
        $query = "SELECT count(id)
        FROM {$this->_tableName}
        WHERE smt_user_id = $smt_user_id  AND `folder_name` like('{$current_folder}')    
        ";
//        echo $query;
        $result = $this->get_var($query);
        return $result;
    }

    public function getTotalShare($type='email') {
        $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
        $card_share_table = $this->prefix . 'st_postcard_share';
        $current_folder = $this->config['folder_generated'];

        $query = "SELECT sum(table1.shared_email)
        FROM {$this->_tableName} card
        LEFT JOIN
        (
        SELECT card.id id , sum(share.number_share) shared_email FROM {$this->_tableName} card 
        LEFT JOIN {$card_share_table} share on share.card_id = card.id 
        WHERE `type_share` like('{$type}') GROUP BY card.id
        ) table1 ON table1.id = card.id 
        WHERE smt_user_id = $smt_user_id  AND `folder_name` like('{$current_folder}')  
        GROUP BY card.smt_user_id
        ";
//        echo $query;
        $result = $this->get_var($query);
        return $result;
    }

    public function getSmtUserId($card_id) {
        $query = "SELECT smt_user_id
        FROM {$this->_tableName}
        WHERE `id` = $card_id        
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function setFeatured($data) {
        if ($data['featured'] == 1) {
            $maxPriority = $this->getMaxPriority();
            $data['priority'] = $maxPriority + 1;
        } else {
            $data['priority'] = NULL;
        }
        return $this->saveRecords($data);
    }

    public function updatePriority($data) {
        $data = $data['priority'];
        $ids = array_keys($data);
        if (is_array($ids)) {
            $result1 = $this->getCardsById($ids);
            $min_cur_priority = $this->getMinMaxPriority($result1);
            $max_cur_priority = $this->getMinMaxPriority($result1, false);

            $min_cur_priority = $min_cur_priority == NULL ? 0 : $min_cur_priority;
            $max_cur_priority = $max_cur_priority == NULL ? 0 : $max_cur_priority;

            $max_new_priority = max($data);
            $min_new_priority = min($data);
            $max_priority = max($min_new_priority, $max_new_priority, $min_cur_priority, $max_cur_priority);
            $min_priority = min($min_new_priority, $max_new_priority, $min_cur_priority, $max_cur_priority);

            $result2 = $this->getFeaturedCard($min_priority, $max_priority);
            $data2 = array();
            if (count($result2) > 0) {
                foreach ($result2 as $key => $value) {
                    if (!in_array($value['id'], $ids)) {
                        $data2[$value['id']] = $value['priority'];
                    }
                }
            }
            asort($data2);

            $min_priority = $this->getMinMaxPriority($result2);
            $i = $min_priority;
            if (count($data2) > 0) {
                foreach ($data2 as $key => $value) {
                    $data2[$key] = $i;
                    $i++;
                }
            }
            asort($data);
            if (count($data) > 0 && count($data2) > 0) {
                foreach ($data as $id1 => $priority1) {
                    $last_priority = 0;
                    foreach ($data2 as $id2 => $priority2) {
                        if ($priority2 == $priority1) {
                            $last_priority = $data2[$id2] = $priority2 + 1;
                        } elseif ($last_priority != 0) {
                            if ($last_priority == $priority2)
                                $last_priority = $data2[$id2] = $priority2 + 1;
                        }
                        //                    echo $last_priority."/$id2<br/>";
                    }
                    //                $data2[$id1] = $priority1;
                }
            }

            if (count($data) > 0) {
                foreach ($data as $id1 => $priority1) {
                    $data2[$id1] = $priority1;
                }
            }

            //        var_dump($data2);
            //        die;

            $success = false;
            if (count($data2) > 0) {
                foreach ($data2 as $key => $value) {
                    $where = array($this->_primaryKey => $key);
                    $value = array('priority' => $value);
                    if ($this->update($this->_tableName, $value, $where)) {
                        $success = true;
                    }
                }
            }
        }
        return $success;
    }

    public function getCardsById($ids) {
        $where = array();
        foreach ($ids as $value) {
            $where[] = "id = $value";
        }
        $where = implode(' OR ', $where);
        $where = 'WHERE ' . $where;
        $query = "SELECT *
        FROM {$this->_tableName}
        $where
        ";
//        echo $query;
        $result = $this->get_results($query, ARRAY_A);
        return $result;
    }

    public function getFeaturedCard($minPriority, $maxPriority) {
        $query = "SELECT *
        FROM {$this->_tableName}
        WHERE `featured` = 1
        AND `priority` >= {$minPriority}
        AND `priority` <= {$maxPriority}
        AND `priority` IS NOT NULL
        AND `folder_name` like('{$this->config['folder_template']}')
        ";
//        echo $query;
        $result = $this->get_results($query, ARRAY_A);
        return $result;
    }

    public function getMinMaxPriority($data, $min = true) {
        $data1 = array();
        foreach ($data as $key => $value) {
            $data1[] = $value['priority'];
        }
        if ($min)
            return min($data1);
        else {
            return max($data1);
        }
    }

    public function getMaxPriority() {
        $smt_user_id = $this->functions->getCurrentSmtUserId($this->config);
        $query = "SELECT max(priority)
        FROM {$this->_tableName}    
        WHERE smt_user_id = $smt_user_id     
        ";
        $result = $this->get_var($query);
        return $result;
    }

    public function getPriority($card_id){
        $query = "SELECT priority
        FROM {$this->_tableName}
        WHERE `id` = $card_id        
        ";
        $result = $this->get_var($query);
        return $result;
    }
}